package net.bolue.sysmng.tblbean;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import net.bolue.sysmng.exception.BolueException;
import net.bolue.sysmng.util.ReflectHelper;

/**
 * 数据表实体抽象类
 * 所有数据表实体类都继承该类
 * @author Administrator
 *
 */
public abstract class TableBean {

	/**
	 * map转换为实体
	 * @param map
	 * @return
	 */
	public abstract TableBean mapToEntry(Map<String,Object> map);
	
	/**
	 * 主键对应的属性集
	 * @return	主键对应的属性集，以逗号间隔。
	 */
	public abstract String keyProps();
	
	/**
	 * 表名
	 * @return
	 */
	public String tableName(){
		String className = Class.class.getName();
		int i = className.lastIndexOf(".");
		String tableName = className.substring(i + 1);
		tableName = tableName.toLowerCase();
		return tableName;
	}
	
	/**
	 * 属性名与列名
	 * @return
	 */
	public Map<String,String> propColMap(){
		Map<String,String> map=new HashMap<String,String>();
		Field[] arrayOfField = this.getClass().getDeclaredFields();
		for (Field field : arrayOfField){
			String fieldName = field.getName();
			map.put(fieldName,fieldName.toUpperCase());
		}
		return map;
	}
	
	public Map<String,Object> entryToMap(){
		Map<String,Object> map = new HashMap<String,Object>();
		Map<String,String> propColMap = propColMap();
		Set<String> keySet = propColMap.keySet();
		Iterator<String> it = keySet.iterator();
		while(it.hasNext()){
			String fieldName = it.next();
			String columnName = propColMap.get(fieldName);
			Object value = null;
			try {
				String getMethodName = ReflectHelper.getMethodName(fieldName);
				Method method = getClass().getMethod(getMethodName, null);
				if(method!=null){
					value = method.invoke(this, null);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			map.put(columnName, value);
		}
		return map;
	}
}
